package xyz.scootaloo.draft.demo;

import java.io.*;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author flutterdash@qq.com
 * @since 2021/5/6 23:21
 */
public class FileTool {

    public static void main(String[] args) throws IOException {
        copy("source.txt", "target.txt");
    }

    private static boolean copy(String sourceFilename, String targetFilename) throws IOException {
        // 从源文件获取输入流
        ClassLoader loader = FileTool.class.getClassLoader();
        // 从目标文件获取输出流
        try (OutputStream targetOut = new FileOutputStream(toFile(targetFilename, loader));
             InputStream sourceIn = loader.getResourceAsStream(sourceFilename)) {
            if (sourceIn == null) {
                System.out.println("路径 `" + sourceFilename + "` 不存在");
                return false; // 复制失败
            }

            byte[] content = sourceIn.readAllBytes();
            targetOut.write(content);
            targetOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    private static File toFile(String filename, ClassLoader loader) throws IOException {
        File targetFile = Paths.get("src/main/resource", filename).toFile();
        if (!targetFile.exists()) {
            targetFile.mkdirs();
            targetFile.createNewFile();
        }
        return targetFile;
    }

}
